package com.tepth.busfix.main.repair.complete;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tepth.busfix.R;
import com.tepth.busfix.base.BaseActivity;
import com.tepth.busfix.bean.reponse.BusInfo;
import com.tepth.busfix.bean.reponse.Trouble;
import com.tepth.busfix.bean.reponse.TroubleContent;
import com.tepth.busfix.bean.request.RepairInfo;
import com.tepth.busfix.config.SpKey;
import com.tepth.busfix.event.DataClearEvent;
import com.tepth.busfix.event.RepairDataRefreshEvent;
import com.tepth.busfix.ic.IcManager;
import com.tepth.busfix.ic.OpenIcEvent;
import com.tepth.busfix.main.home.HomeActivity;
import com.tepth.busfix.main.login.LoginActivity;
import com.tepth.busfix.main.repair.NFCDialogActivity;
import com.tepth.busfix.tools.AESUtils;
import com.tepth.busfix.tools.SPUtils;
import com.tepth.busfix.tools.ToastUtils;
import com.tepth.busfix.tools.UsbUtil;
import com.tepth.busfix.view.dialog.DialogDelegate;
import com.tepth.busfix.view.dialog.SweetAlertDialogDelegate;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.tepth.busfix.main.repair.NFCDialogActivity.NFC_RESULTCODE;

/**
 * Created by zhangyu on 2017/7/13.
 */

public class CompletePunchCardActivity extends BaseActivity implements CompletePunchCardContract.View {
    private static final String EXTRA_NAME = "troubles";
    private static final String BUS_INFO_ID = "busInfo";
    private static final String COMPLETE_ID = "completeId";
    private static final int REQUEST_CARD_FINISH = 4;
    private static final int REQUEST_CARD_REWORK = 5;

    public static void startActivity(Activity activity, ArrayList<Trouble> list
            , BusInfo busInfo, ArrayList<Long> longs) {
        Intent intent = new Intent(activity, CompletePunchCardActivity.class);
        intent.putExtra(EXTRA_NAME, list);
        intent.putExtra(BUS_INFO_ID, busInfo);
        intent.putExtra(COMPLETE_ID, longs);
        activity.startActivity(intent);
    }

    @BindView(R.id.list_view)
    ExpandableListView mExpandableListView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    private OperatorAdapter mOperatorAdapter;
    private BusInfo mBusInfo;
    private RepairInfo mRepairInfo;
    private CompletePunchCardPresenter mPresenter;
    private DialogDelegate dialogDelegate;
    private ArrayList<Long> mHasCompleteTroubleList = new ArrayList<>();
    private PunchState mPunchState = PunchState.finish;
    private enum PunchState{
        finish,
        rework
    }
    @Override
    public int getLayoutId() {
        return R.layout.activity_complete_punch_card;
    }

    @Override
    public void initView() {

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Intent intent = getIntent();
        mBusInfo = (BusInfo) intent.getSerializableExtra(BUS_INFO_ID);
        ArrayList<Trouble> troubles = (ArrayList<Trouble>) intent.getSerializableExtra(EXTRA_NAME);
        ArrayList<Long> longs = (ArrayList<Long>) intent.getSerializableExtra(COMPLETE_ID);
//        Map<Long, Trouble> map = new HashMap<>();
//        for (TroubleContent troubleContent : troubleContents1) {
//            Trouble trouble = map.get(troubleContent.getTroubleId());
//            if (trouble == null) {
//                trouble = new Trouble();
//                List<TroubleContent> troubleContents = new ArrayList<>();
//                troubleContents.add(troubleContent);
//                trouble.setListContent(troubleContents);
//                trouble.setTroubleTypeId(troubleContent.getTroubleTypeId());
//                trouble.setId(troubleContent.getTroubleId());
//                trouble.setName(troubleContent.getTroubleTypeName());
//                if (longs.contains(trouble.getId())) {
//                    trouble.setChecked(true);
//                }
//                map.put(troubleContent.getTroubleId(), trouble);
//            } else {
//                trouble.getListContent().add(troubleContent);
//            }
//        }
//        ArrayList<Trouble> troubles = new ArrayList<>(map.values());
        for (Trouble trouble : troubles) {
            if (longs.contains(trouble.getId())) {
                trouble.setChecked(true);
            } else {
                trouble.setChecked(false);
            }
            if (trouble.getListContent() == null) {
                trouble.setListContent(new ArrayList<TroubleContent>());
            }
        }
        mOperatorAdapter = new OperatorAdapter(this, troubles);
        mExpandableListView.setAdapter(mOperatorAdapter);
        for (int i = 0; i < troubles.size(); i++) {
            mExpandableListView.expandGroup(i);
        }
        tvTitle.setText("作业列表");
        dialogDelegate = new SweetAlertDialogDelegate(this);
        // mExpandableListView.setGroupIndicator(null);
        EventBus.getDefault().register(this);
    }

    @Override
    public void setPresenter() {
        mPresenter = new CompletePunchCardPresenter();
        CompletePunchCardModel mModel = new CompletePunchCardModel();
        mPresenter.setVM(this, mModel);
    }

    @OnClick(R.id.btn_do_return)
    public void onDoReturn() {
        mHasCompleteTroubleList.clear();
        List<Trouble> list = mOperatorAdapter.getDatas();
        List<RepairInfo.ListTroubleBean> ListTroubleBean = new ArrayList<>();
        for (Trouble trouble : list) {
            if (!trouble.isChecked()) {
                // tempList.add(trouble);
                long troubleId = trouble.getId();
                RepairInfo.ListTroubleBean troubleBean = new RepairInfo.ListTroubleBean();
                troubleBean.setId(troubleId);
                List<TroubleContent> troubleContents = trouble.getListContent();
                for (TroubleContent troubleContent : troubleContents) {
                    troubleContent.setRework(true);
                }
                troubleBean.setListContent(troubleContents);
                ListTroubleBean.add(troubleBean);
            } else {
                mHasCompleteTroubleList.add(trouble.getId());
            }
        }
        mRepairInfo = new RepairInfo();
        mRepairInfo.setId(mBusInfo.getId());
        mRepairInfo.setListTrouble(ListTroubleBean);
        mRepairInfo.setListConfirm(new ArrayList<RepairInfo.ListConfirmBean>());
        if (!ListTroubleBean.isEmpty()) {
            dialogDelegate.showWarningDialog("作业返工", "确认返工么？", new DialogDelegate.OnDialogListener() {
                @Override
                public void onClick() {
                    if (UsbUtil.hasUsbDevice(CompletePunchCardActivity.this)) {
//                        startActivityForResult(new Intent(CompletePunchCardActivity.this, ICDialogActivity2.class),
//                                REQUEST_CARD_REWORK);
                        mPunchState = PunchState.rework;
                        IcManager.getInstance().openDevice();
                        dialogDelegate.changeText("","");
                        dialogDelegate.changeToProgressType( "正在打开设备...");
                        dialogDelegate.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                IcManager.getInstance().leisureDevice();
                            }
                        });
                    } else {
                        startActivityForResult(new Intent(CompletePunchCardActivity.this, NFCDialogActivity.class),
                                REQUEST_CARD_REWORK);
                    }
                }
            });
        } else {
            ToastUtils.showToast(this, "没有需要返工的作业项!");
        }
    }

    @OnClick(R.id.btn_do_work)
    public void onDoComplete() {
        List<Trouble> list = mOperatorAdapter.getDatas();
        int count = 0;
        for (Trouble trouble : list) {
            if (!trouble.isChecked()) {
                count++;
            }
        }
        if (count > 0) {
            ToastUtils.showToast(this, "请确认所有作业已通过!");
        } else {
            if (UsbUtil.hasUsbDevice(this)) {
//                startActivityForResult(new Intent(this, ICDialogActivity2.class),
//                        REQUEST_CARD_FINISH);
                mPunchState = PunchState.finish;
                IcManager.getInstance().openDevice();
                dialogDelegate.showProgressDialog(true, "正在打开设备...");
                dialogDelegate.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        IcManager.getInstance().leisureDevice();
                    }
                });
            } else {
                startActivityForResult(new Intent(this, NFCDialogActivity.class),
                        REQUEST_CARD_FINISH);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == NFC_RESULTCODE) {
            byte[] displayContents = data.getByteArrayExtra("BarCodeContents");
            try {
                String contents = new String(displayContents, "utf-8");
                String result = AESUtils.code_desEncrypt(contents);
                if (result.isEmpty()) {
                    ToastUtils.showToast(this, "保存失败");
                } else {
                    String[] results = result.split("_");
                    if (result.length() < 2) {
                        ToastUtils.showToast(this, "保存失败");
                    } else {
                        String personNumber = results[0];
                        String personName = results[1];
                        if (requestCode == REQUEST_CARD_FINISH) {//竣检打卡
                            mRepairInfo = new RepairInfo();
                            mRepairInfo.setId(mBusInfo.getId());
                            List<RepairInfo.ListConfirmBean> list = new ArrayList<>();
                            RepairInfo.ListConfirmBean listConfirmBean = new RepairInfo.ListConfirmBean();

                            listConfirmBean.setConfirmType(3);
                            listConfirmBean.setConfirmPerson(new
                                    RepairInfo.ListConfirmBean.ConfirmPersonBean(0, personNumber));
                            list.add(listConfirmBean);
                            mRepairInfo.setListConfirm(list);
                            mRepairInfo.setListTrouble(new ArrayList<RepairInfo.ListTroubleBean>());
                            mPresenter.postRepair();
                        } else if (requestCode == REQUEST_CARD_REWORK) {//作业返工
                            mPresenter.postRework();
                        }
                        dialogDelegate.showProgressDialog(true, "正在提交...");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onNetworkError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        dialogDelegate.stopProgressWithWarning(msg, msg, new DialogDelegate.OnDialogListener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(CompletePunchCardActivity.this, LoginActivity.class);
                intent.putExtra("reload", "reload");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(this, SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public String getRepairInfo() {
        Gson gson = new Gson();
        String str = gson.toJson(mRepairInfo);
        Log.e("TAG", str);
        return str;
    }

    @Override
    public void postRepairInfoSucceed() {
        dialogDelegate.changeText("","");
        dialogDelegate.stopProgressWithSuccess("打卡成功", "打卡成功", new DialogDelegate.OnDialogListener() {
            @Override
            public void onClick() {
                dialogDelegate.clearDialog();
                EventBus.getDefault().post(new DataClearEvent());
                Intent intent = new Intent(CompletePunchCardActivity.this, HomeActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        dialogDelegate.getDialog().setCancelable(false);
        dialogDelegate.getDialog().setCanceledOnTouchOutside(false);
    }

    @Override
    public void postReworkSucceed() {
        dialogDelegate.changeText("","");
        dialogDelegate.stopProgressWithSuccess("返工成功", "返工成功", new DialogDelegate.OnDialogListener() {
            @Override
            public void onClick() {
                dialogDelegate.clearDialog();
                EventBus.getDefault().post(new RepairDataRefreshEvent(mHasCompleteTroubleList));
            }
        });
        dialogDelegate.getDialog().setCancelable(false);
        dialogDelegate.getDialog().setCanceledOnTouchOutside(false);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }
    @Subscribe(priority = 1)
    public void onICEvent(final OpenIcEvent event) {
        //接收了该事件就拦截掉 不会继续往优先级小于priority的地方传递
        EventBus.getDefault().cancelEventDelivery(event);
        if (!event.isSuccess) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (dialogDelegate != null) {
                        dialogDelegate.changeText(event.mTitle, (String) event.mObject);
                    }
                }
            });
        } else {
            byte[] displayContents = (byte[]) event.mObject;
            String[] result = analysisData(new String(displayContents));
            if(result != null){
                switch (mPunchState){
                    case finish:
                        finishCheck(result);
                        break;
                    case rework:
                        rework(result);
                        break;
                }
            }
        }
    }

    private String[] analysisData(String data) {
        String result;
        try {
            result = AESUtils.code_desEncrypt(data);

            if (result.isEmpty()) {
                ToastUtils.showToast(this, "AES解码失败");
                return null;
            }
            String[] results = result.split("_");
            if (result.length() < 2) {
                ToastUtils.showToast(this, "数组长度小于2");
                return null;
            }
            return results;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 竣检
     */
    private void finishCheck(String[] result){
        String personNumber = result[0];
        mRepairInfo = new RepairInfo();
        mRepairInfo.setId(mBusInfo.getId());
        List<RepairInfo.ListConfirmBean> list = new ArrayList<>();
        RepairInfo.ListConfirmBean listConfirmBean = new RepairInfo.ListConfirmBean();

        listConfirmBean.setConfirmType(3);
        listConfirmBean.setConfirmPerson(new
                RepairInfo.ListConfirmBean.ConfirmPersonBean(0, personNumber));
        list.add(listConfirmBean);
        mRepairInfo.setListConfirm(list);
        mRepairInfo.setListTrouble(new ArrayList<RepairInfo.ListTroubleBean>());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (dialogDelegate != null) {
                    dialogDelegate.changeText("读卡成功", "正在提交...");
                }
            }
        });
        mPresenter.postRepair();
    }
    /**
     * 返工
     */
    private void rework(String[] result){
        String personNumber = result[0];
        mRepairInfo = new RepairInfo();
        mRepairInfo.setId(mBusInfo.getId());
        List<RepairInfo.ListConfirmBean> list = new ArrayList<>();
        RepairInfo.ListConfirmBean listConfirmBean = new RepairInfo.ListConfirmBean();

        listConfirmBean.setConfirmType(3);
        listConfirmBean.setConfirmPerson(new
                RepairInfo.ListConfirmBean.ConfirmPersonBean(0, personNumber));
        list.add(listConfirmBean);
        mRepairInfo.setListConfirm(list);
        mRepairInfo.setListTrouble(new ArrayList<RepairInfo.ListTroubleBean>());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (dialogDelegate != null) {
                    dialogDelegate.changeText("读卡成功", "正在提交...");
                }
            }
        });
        mPresenter.postRework();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
